package com.kc.gb.device.tools;

import cn.hutool.core.util.IdUtil;
import com.kc.gb.device.JavaFxStarter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.net.SocketException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class SSEStore {

    private static Set<SseEmitter> STATION_EMITTER = new HashSet<>();

    /**
     * 新增
     * @param emitter
     */
    public static synchronized void addEmitter(SseEmitter emitter){
        STATION_EMITTER.add(emitter);
    }

    public static synchronized void removeEmitter(SseEmitter emitter){
        STATION_EMITTER.remove(emitter);
    }

    /**
     * 通知界面刷新
     */
    public static synchronized void sendRefreshEvent(String publisher) throws SocketException {
        String eventId = IdUtil.fastSimpleUUID();
        String eventName = "RefreshUI";
        SseEmitter.SseEventBuilder builder = SseEmitter.event()
                .id(eventId)
                .name(eventName)
                .data(publisher)
                .reconnectTime(1000);
        Set<SseEmitter> emitters = STATION_EMITTER;
        if(CollectionUtils.isNotEmpty(emitters)){
            for(SseEmitter emitter : emitters){
                try {
                    log.info("SseEmitter: publisher:{} send refresh event",publisher);
                    emitter.send(builder.build());
                    log.info("SseEmitter: publisher:{} send success",publisher);
                } catch (IOException e) {
                    log.info("SseEmitter: publisher: {} send fail:{}",publisher,e.getMessage(),e);
                    emitter.completeWithError(e);
                }
            }
        }
        // JavaFx 使用的浏览器不兼容 sse, 使用 WebEngine 进行兜底
        // 调用界面的数据刷新接口, 防止reload造成的闪屏
        JavaFxStarter.refreshData();
    }
}
